//
// Copyright (c) 2019-2023 BPer
//

#include "BPerMetaplayer.h"
#include <bperutil/sys/BPerSocket.h>
#include <bperutil/sys/BPerLog.h>
#include <bperutil/sys/BPerMath.h>
#include "BPerLvglDef.h"
BPerMetaplayer::BPerMetaplayer()

{

	m_context=new BPerContext();
	m_context->init();

	m_context->synMgr.session->playBuffer=(BPerSynBuffer*)bPer_calloc(sizeof(BPerSynBuffer),1);
	bPer_create_synBuffer(m_context->synMgr.session->playBuffer);

	m_context->avinfo.sys.mediaServer=BPer_Server_Srs;//BPer_Server_Srs/BPer_Server_Zlm
	m_context->avinfo.rtc.rtcSocketProtocol=BPer_Socket_Protocol_Udp;//

	m_context->avinfo.rtc.rtcLocalPort=10000+bPer_random()%15000;
	memset(m_context->avinfo.rtc.localIp,0,sizeof(m_context->avinfo.rtc.localIp));
	bPer_getLocalInfo(m_context->avinfo.sys.familyType,m_context->avinfo.rtc.localIp);
	m_player= BPerPlayerHandle::createPlayerHandle(m_context,this);
	bPer_setLogLevel(5);
	bPer_setLogFile(1);

	char s[128]={0};

	sprintf(s,"webrtc://%s:1985/live/livestream",m_context->avinfo.rtc.localIp);
	bPer_trace("\nurl===%s",s);
	bPer_lvgl_setUrlText(s);

	m_isStartplay=false;

	m_context->avinfo.rtc.iceCandidateType=BPerIceHost;
	m_context->avinfo.rtc.turnSocketProtocol=BPer_Socket_Protocol_Udp;

	m_context->avinfo.rtc.enableAudioBuffer=BPerTrue; //use audio buffer
	m_context->avinfo.audio.enableAudioFec=BPerFalse; //srs not use audio fec

}

BPerMetaplayer::~BPerMetaplayer()
{

	m_videoThread->m_syn=NULL;

	bPer_delete(m_player);
	bPer_closeLogFile();
	bPer_delete(m_context);

}


void BPerMetaplayer::success(){

}
void BPerMetaplayer::failure(int32_t errcode){



}

void BPerMetaplayer::initVideoThread(BPerRecordThread *prt){
	m_videoThread=prt;
	m_videoThread->initPara();
	m_videoThread->m_syn= m_context->synMgr.session->playBuffer;

}

void BPerMetaplayer::on_m_b_play_clicked()
{
	if(!m_isStartplay){
		m_videoThread->m_syn=m_context->synMgr.session->playBuffer;
		m_videoThread->m_syn->resetVideoClock(m_videoThread->m_syn->session);
		int32_t err=BPer_Ok;
		char* url=bPer_lvgl_get_urlstr();

		err=m_player->play(url);

		if(err==BPer_Ok){
			bPer_lvgl_setPlayButtonStr("stop");
			m_isStartplay=!m_isStartplay;
			m_videoThread->m_isRender=true;
		}else{
			bPer_error("play url error!");
			m_videoThread->m_isRender=false;
		}

	}else{
		m_videoThread->m_isRender=false;

		bPer_lvgl_setPlayButtonStr("play");
		bPer_usleep(50*1000);
		if(m_player) m_player->stopPlay();

		m_isStartplay=!m_isStartplay;

	}
}






